package com.insight.modules.umpPwdManage.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import com.insight.common.api.vo.Result;
import com.insight.common.aspect.annotation.AutoLog;
import com.insight.common.system.base.controller.JeecgController;
import com.insight.common.system.query.QueryGenerator;
import com.yuanqiao.insight.acore.system.entity.SysDictItem;
import com.yuanqiao.insight.acore.system.service.ISysDictService;
import com.insight.modules.umpPwdManage.entity.UmpPwdManage;
import com.insight.modules.umpPwdManage.mapper.UmpPwdManageMapper;
import com.insight.modules.umpPwdManage.service.IUmpPwdManageService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * 登录密码配置控制器
 * 提供分页查询、新增、编辑、删除、导出导入等接口
 *
 * @Description: 登录密码配置
 * @Author: jeecg-boot
 * @Date: 2021-08-10
 * @Version: V1.0
 */
@Api(tags = "登录密码配置")
@RestController
@RequestMapping("/umpPwdManage/umpPwdManage")
@Slf4j
public class UmpPwdManageController extends JeecgController<UmpPwdManage, IUmpPwdManageService> {

    @Autowired
    private IUmpPwdManageService umpPwdManageService;

    @Autowired
    private UmpPwdManageMapper umpPwdManageMapper;

    @Autowired
    ISysDictService sysDictService;

    /**
     * 分页查询登录密码配置列表
     *
     * @param umpPwdManage 查询条件封装实体
     * @param pageNo       当前页码，默认1
     * @param pageSize     每页记录数，默认10
     * @param req          HttpServletRequest对象，包含请求参数
     * @return 分页查询结果封装在Result对象中
     */
    @ApiOperation(value = "登录密码配置-分页列表查询", notes = "登录密码配置-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(UmpPwdManage umpPwdManage,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        // 使用QueryGenerator自动构造查询条件Wrapper，支持多种条件动态拼接
        QueryWrapper<UmpPwdManage> queryWrapper = QueryGenerator.initQueryWrapper(umpPwdManage, req.getParameterMap());
        Page<UmpPwdManage> page = new Page<>(pageNo, pageSize);
        // 分页查询
        IPage<UmpPwdManage> pageList = umpPwdManageService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 查询常规密码配置，返回第一条数据，且清空压缩密码字段避免泄露
     *
     * @return 常规密码配置实体
     */
    @GetMapping(value = "/list2")
    public Result<?> queryPageList2() {
        UmpPwdManage umpPwdManage = new UmpPwdManage();
        List<UmpPwdManage> list = umpPwdManageService.list();
        for (UmpPwdManage item : list) {
            // 设置名称为常规密码名称
            item.setName(item.getCommonly());
            BeanUtils.copyProperties(item, umpPwdManage);
            // 清空压缩密码字段，避免敏感信息泄露
            umpPwdManage.setZipPwd("");
            break; // 只取第一条
        }
        return Result.OK(umpPwdManage);
    }

    /**
     * 查询高级密码配置，返回第一条数据
     *
     * @return 高级密码配置实体
     */
    @GetMapping(value = "/list3")
    public Result<?> queryPageList3() {
        UmpPwdManage umpPwdManage = new UmpPwdManage();
        List<UmpPwdManage> list = umpPwdManageService.list();
        for (UmpPwdManage item : list) {
            // 设置名称为高级密码名称
            item.setName(item.getSerious());
            BeanUtils.copyProperties(item, umpPwdManage);
            break; // 只取第一条
        }
        return Result.OK(umpPwdManage);
    }

    /**
     * 添加新的密码配置
     *
     * @param umpPwdManage 密码配置实体，前端传入
     * @return 操作结果
     */
    @AutoLog(value = "登录密码配置-添加")
    @ApiOperation(value = "登录密码配置-添加", notes = "登录密码配置-添加")
    @PostMapping(value = "/add")
    public Result<?> add(@RequestBody UmpPwdManage umpPwdManage) {
        // 验证密码复杂度配置，必须启用至少3个复杂度条件
        if (umpPwdManage.getCapitalize() + umpPwdManage.getSpecial() +
                umpPwdManage.getLowercase() + umpPwdManage.getHasNum() < 3) {
            return Result.error("至少选择3个复杂程度！");
        }

        // 继承现有的压缩密码和加密标识，避免覆盖
        UmpPwdManage allPwdManage = umpPwdManageMapper.findAllPwdManage();
        umpPwdManage.setZipPwd(allPwdManage.getZipPwd());
        umpPwdManage.setIsEncry(allPwdManage.getIsEncry());

        // 保存新配置
        umpPwdManageService.save(umpPwdManage);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑已有密码配置
     *
     * @param umpPwdManage 编辑后的密码配置实体
     * @return 操作结果
     */
    @AutoLog(value = "导出密码配置-编辑")
    @ApiOperation(value = "登录密码配置-编辑", notes = "登录密码配置-编辑")
    @PutMapping(value = "/edit")
    public Result<?> edit(@RequestBody UmpPwdManage umpPwdManage) {
        UmpPwdManage allPwdManage = umpPwdManageMapper.findAllPwdManage();

        // 校验旧密码是否正确（防止非法修改）
        if (StringUtils.isNotEmpty(allPwdManage.getZipPwd()) &&
                StringUtils.isNotEmpty(umpPwdManage.getOldPwd()) &&
                !umpPwdManage.getOldPwd().equals(allPwdManage.getZipPwd())) {
            return Result.error("旧密码验证失败，请重试");
        }

        // 更新配置
        umpPwdManageService.updateById(umpPwdManage);
        return Result.OK("编辑成功!");
    }

    /**
     * 根据ID删除密码配置
     *
     * @param id 密码配置ID
     * @return 删除结果
     */
    @AutoLog(value = "登录密码配置-通过id删除")
    @ApiOperation(value = "登录密码配置-通过id删除", notes = "登录密码配置-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        umpPwdManageService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除密码配置，支持逗号分隔多个ID
     *
     * @param ids 多个密码配置ID，逗号分隔
     * @return 删除结果
     */
    @AutoLog(value = "登录密码配置-批量删除")
    @ApiOperation(value = "登录密码配置-批量删除", notes = "登录密码配置-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        umpPwdManageService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 根据ID查询单条密码配置信息
     *
     * @param id 密码配置ID
     * @return 查询结果
     */
    @AutoLog(value = "登录密码配置-通过id查询")
    @ApiOperation(value = "登录密码配置-通过id查询", notes = "登录密码配置-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        UmpPwdManage umpPwdManage = umpPwdManageService.getById(id);
        if (umpPwdManage == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(umpPwdManage);
    }

    /**
     * 导出密码配置数据为Excel文件
     *
     * @param request  请求对象
     * @param umpPwdManage 查询条件
     * @return 导出视图
     */
    @ApiOperation(value = "导出excel", notes = "导出密码配置为Excel")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, UmpPwdManage umpPwdManage) {
        return super.exportXls(request, umpPwdManage, UmpPwdManage.class, "登录密码配置");
    }

    /**
     * 从Excel导入密码配置数据
     *
     * @param request  请求对象
     * @param response 响应对象
     * @return 导入结果
     */
    @ApiOperation(value = "通过excel导入数据", notes = "通过excel导入密码配置")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, UmpPwdManage.class);
    }

    /**
     * 更新压缩加密密码（zip密码）
     * 只更新zipPwd字段，其他字段保持不变，避免误覆盖
     *
     * @param umpPwdManage 包含新的zipPwd字段的实体
     * @return 操作结果
     */
    @AutoLog(value = "导出加密-提交")
    @PostMapping(value = "/addZip")
    public Result<?> addZip(@RequestBody UmpPwdManage umpPwdManage) {
        UmpPwdManage allPwdManage = umpPwdManageMapper.findAllPwdManage();

        // 复制除zipPwd外的所有字段，保证数据完整
        umpPwdManage.setId(allPwdManage.getId());
        umpPwdManage.setCreateTime(allPwdManage.getCreateTime());
        umpPwdManage.setOverTime(allPwdManage.getOverTime());
        umpPwdManage.setPwdMin(allPwdManage.getPwdMin());
        umpPwdManage.setErrorNum(allPwdManage.getErrorNum());
        umpPwdManage.setUnLock(allPwdManage.getUnLock());
        umpPwdManage.setCapitalize(allPwdManage.getCapitalize());
        umpPwdManage.setLowercase(allPwdManage.getLowercase());
        umpPwdManage.setHasNum(allPwdManage.getHasNum());
        umpPwdManage.setSpecial(allPwdManage.getSpecial());
        umpPwdManage.setCommonly(allPwdManage.getCommonly());
        umpPwdManage.setSerious(allPwdManage.getSerious());
        umpPwdManage.setUpdateTimes(allPwdManage.getUpdateTimes());
        umpPwdManage.setStartTime(allPwdManage.getStartTime());
        umpPwdManage.setStopTime(allPwdManage.getStopTime());
        umpPwdManage.setStartIp(allPwdManage.getStartIp());
        umpPwdManage.setStopIp(allPwdManage.getStopIp());
        umpPwdManage.setMac(allPwdManage.getMac());

        umpPwdManageService.updateById(umpPwdManage);
        return Result.OK("添加成功！");
    }

    /**
     * 通过字典编码查询对应的数据字典项
     *
     * @param code 字典编码
     * @return 字典项列表
     */
    @ApiOperation(value = "登录密码配置-通过字典code查询", notes = "登录密码配置-通过字典code查询")
    @GetMapping(value = "/findSysDictItem")
    public Result<?> findSysDictItem(@RequestParam(name = "code", required = true) String code) {
        List<SysDictItem> sysDictItem = sysDictService.findSysDictItemByCode(code);

